package main

import (
	"fmt"
	"io"
	"learn-zinx/znet"
	"net"
	"time"
)

type Client struct {
	Id   uint32
	Conn net.Conn
	msg  chan []byte
}

func NewClient(id uint32, conn net.Conn) *Client {
	return &Client{
		Id:   id,
		Conn: conn,
		msg:  make(chan []byte),
	}
}

func (c *Client) SendMsg(msg string) {
	//发封包message消息
	dp := znet.NewDataPack()
	data, _ := dp.Pack(znet.NewMsgPackage(0, []byte(msg)))
	_, err := c.Conn.Write(data)
	if err != nil {
		fmt.Println("write error err ", err)
		return
	}
}

func (c *Client) ReadMsg() {
	//先读出流中的head部分
	for {
		dp := znet.NewDataPack()
		headData := make([]byte, dp.GetHeadLen())
		_, err := io.ReadFull(c.Conn, headData) //ReadFull 会把msg填充满为止
		if err != nil {
			fmt.Println("read head error")
			return
		}
		//将headData字节流 拆包到msg中
		msgHead, err := dp.Unpack(headData)
		if err != nil {
			fmt.Println("server unpack err:", err)
			return
		}

		if msgHead.GetDataLen() > 0 {
			//msg 是有data数据的，需要再次读取data数据
			msg := msgHead.(*znet.Message)
			msg.Data = make([]byte, msg.GetDataLen())

			//根据dataLen从io中读取字节流
			_, err := io.ReadFull(c.Conn, msg.Data)
			if err != nil {
				fmt.Println("server unpack data err:", err)
				return
			}
			c.msg <- msg.Data
			fmt.Println("==> Recv Msg: ID=", msg.Id, ", len=", msg.DataLen, ", data=", string(msg.Data))
		}
	}
}

/*
模拟客户端
*/
func main() {

	fmt.Println("Client Test ... start")
	//3秒之后发起测试请求，给服务端开启服务的机会
	time.Sleep(3 * time.Second)

	for i := 0; i < 10; i++ {
		conn, err := net.Dial("tcp", "127.0.0.1:7777")
		if err != nil {
			return
		}
		client := NewClient(uint32(i), conn)
		go client.SendMsg(fmt.Sprintf("client %d writer", i))
		go client.ReadMsg()
	}
}
